/**
 * @author mdc
 * @date 2017年7月5日 下午3:41:31
 */
package com0oky.httpkit.test;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.ContentType;
import org.junit.Test;

import com0oky.httpkit.http.HttpKit;
import com0oky.httpkit.http.ResponseWrap;
import com0oky.httpkit.http.request.RequestBase;
import com0oky.httpkit.http.request.RequestFuture;

/**
 * @author mdc
 * @date 2017年7月5日 下午3:41:31
 */
public class BaiduCloudMultThread {
	
	@SuppressWarnings("unchecked")
	@Test
	public void requestCloudDomain(){
		
		String url = "https://cloud.baidu.com/api/bcd/search/status";
		String Referer = "https://cloud.baidu.com/product/bcd/search.html?keyword=";
		String req = "{\"domainNames\":[{\"label\":\"%s\",\"tld\":\"com\"}]}";
		String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36";

		ExecutorService service = Executors.newScheduledThreadPool(30);
		
		ResponseHandler<CheckDomainResult> resp = new ResponseHandler<CheckDomainResult>() {
			@Override
			public CheckDomainResult handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
				ResponseWrap responseWrap = new ResponseWrap(response);
				return responseWrap.getJson(CheckDomainResult.class);
			}
		};
		
		int count = 100;
		RequestFuture<CheckDomainResult>[] futures = new RequestFuture[count];
		
		try {
			
			for (int i = 0; i < count; i++) {
				String domainLabel = "aaa" + i;
				
				RequestBase request = HttpKit.post(url)
				.setParameter(String.format(req, domainLabel))
				.setContentType(ContentType.APPLICATION_JSON)
				.setHeader("Origin", "https://cloud.baidu.com")
				.setUserAgent(userAgent)
				.addHeader("Referer", Referer + domainLabel);

				RequestFuture<CheckDomainResult> future = request.executeCallback(service, resp);
				futures[i] = future;
			}
			
			//获取结果
			for (RequestFuture<CheckDomainResult> result : futures) {
				Accurate accurate = result.get().getResult().getAccurate()[0];
				System.out.println("域名:" + accurate.getDomainName() + " 状态:" +accurate.getStatus());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			service.shutdown();
		}
	}
}
